<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>迭代器</title>
</head>
<body>
    
</body>

<script>
    //在symbol对象存在迭代器方法，作用是提供for ... of进行迭代功能
    //具备迭代器方法的对象 ：array arguments set map string typedArray nodeList
    const arr = [`1`,`2`,`3`,`4`];
    for (const iterator of arr) {
        console.log(iterator);
    }

    //其原理是 设置了一个指针，每次迭代，都会调用对象的next方法 done为true时表示迭代完成
    let iterator = arr[Symbol.iterator]();
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());
    console.log(iterator.next());


    //实例 自定义数组遍历
    const banji = {
        name:'一班',
        stus:[
            '小明',
            '小红',
            '小白',
            '小黑'
        ],
        [Symbol.iterator](){

            let _this = this;
            //声明索引
            let index = 0;
            return{
                next: function(){
                    if(index<_this.stus.length){
                        const result={value: _this.stus[index],done: false};
                        index++;//索引增加
                        return result;//返回结果
                    }else{
                        return {value: undefined,done: true};
                    }
                }
            };
        }
    }

    for (let iterator of banji) {
        console.log(iterator);
    }
</script>
</html>